package auctionServer.utilities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import org.bouncycastle.util.encoders.Base64;

public class TcpServerConnection {
	private int tcpPort;

	private static Socket connectedSocket;
	private PrintWriter out;
    private BufferedReader in;	

    public TcpServerConnection(int TcpPort,Socket connSocket){
		this.tcpPort=TcpPort;
		connectedSocket=connSocket;

		try {
			out = new PrintWriter((connectedSocket).getOutputStream(), true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			in = new BufferedReader(new InputStreamReader(connectedSocket.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void disconnect(){
		try {
			out.close();
			in.close();
			connectedSocket.close();
		} catch (IOException e) {
			System.out.println("I/O exception at client side socket .close()");
		}
	}

	public byte[] getMessage(){
		try {
			byte[] message = Base64.decode(in.readLine());
			return message;
		} catch (IOException e) {
			return "I/O Read Error at client Side at the Socket".getBytes();
		}
	}
	
	public void appendMessage(byte[] message){
		byte[] messageBase64 = Base64.encode(message);
		out.println(new String(messageBase64));
	}

	public int getTcpPort(){
		return tcpPort;
	}
	
	public boolean isAlive(){
		return connectedSocket.isConnected();
	}
}
